﻿using DeathByCaptcha;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using VisapointLibrary.Controllers;

namespace VisaPoint
{
    public partial class FrmThreadCaptcha : Form
    {
        CaptchaSocket captcha = new CaptchaSocket();
        public FrmThreadCaptcha()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }
        bool Stop = false;
        private void btnRun_Click(object sender, EventArgs e)
        {
            
            new Thread(new ThreadStart(Start)).Start();
            //captcha.server.OnWriteLine += new Server.OnConsole(WriteLog);
            //WriteLog("Start Captcha: ");
            //string content = captcha.getCaptcha(Application.StartupPath + @"\capchar.jpg");
            //WriteLog("Captcha: " + content);
            
        }
        private void CopyCaptcha()
        {
            string fileCapchar = Application.StartupPath + @"\capchar.jpg";
            string FIleDest = Application.StartupPath + @"\captcha\capchar.jpg";
            while (File.Exists(FIleDest))
            {
                Thread.Sleep(200);
            }
            File.Copy(fileCapchar, Application.StartupPath + @"\captcha\capchar.jpg", true);
        }
        private void Start()
        {
            while (!Stop)
            {
                //string file = Application.StartupPath + "\\captcha\\capchar.jpg";
                //if (File.Exists(file))
                //{
                //    getCapchar(file);
                //    WriteLog("done");
                //}
                //Thread.Sleep(100);
                CopyCaptcha();
                Thread.Sleep(1000);
            }
        }
        public void WriteLog(String message)
        {
            FileStream _stream;
            try
            {
                string pathFolder = Application.StartupPath + "\\Log\\";
                if (!Directory.Exists(pathFolder))
                {
                    Directory.CreateDirectory(pathFolder);
                }
                String Path = pathFolder + string.Format("{0:yyyy-MM-dd}", DateTime.Now) + ".txt";
                //String Path = HttpContext.Current.Server.MapPath("~/") + "200302.txt";
                if (!File.Exists(Path))
                    _stream = File.Create(Path);
                else
                    _stream = new FileStream(Path, FileMode.Append);

                StreamWriter sw = new StreamWriter(_stream);
                string content = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + ":" + message + Environment.NewLine;
                sw.WriteLine(content);
                rtbLog.AppendText(content);
                rtbLog.SelectionStart = rtbLog.Text.Length;
                rtbLog.ScrollToCaret();
                //sw.Flush();
                sw.Close();
                sw.Dispose();
                _stream.Close();
                _stream.Dispose();
            }
            catch (System.Exception ex)
            {
            }
        }
        private static System.Drawing.Image cropImage(System.Drawing.Image img, Rectangle cropArea)
        {
            Bitmap bmpImage = new Bitmap(img);
            return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
        public string getCapchar(string PathFile)
        {
            WriteLog("Start Captcha: ");
            File.Delete(Application.StartupPath + "\\captcha\\captcha.txt");
            System.Drawing.Image image = System.Drawing.Image.FromFile(PathFile);
            try
            {

                //webClient.DownloadFile(LinkCaptcha, PathFile);
                Client client = (Client)new SocketClient("hieupn", "abCd1234");

                Captcha captcha = client.Decode(imageToByteArray(cropImage(image, new Rectangle(new Point(0, 0), new Size(250, 60)))), 20000);
                if (captcha != null && captcha.Solved && captcha.Correct)
                {

                    // Report the CAPTCHA if solved incorrectly.
                    // Make sure the CAPTCHA was in fact incorrectly solved!
                    Boolean IsSuccess = client.Report(captcha);
                    WriteLog("Captcha: " + captcha.Text);
                    image.Dispose();
                    File.WriteAllText(Application.StartupPath+"\\captcha\\captcha.txt",captcha.Text);
                    return captcha.Text.ToUpper();
                }
            }
            catch (DeathByCaptcha.Exception ex)
            {
                WriteLog("Error Captcha: " + ex.Message);
                if (ex.Message.Equals("CAPTCHA was rejected due to service overload"))
                {
                    return getCapchar(PathFile);
                }
            }
            finally
            {
                
                image.Dispose();
                File.Delete(PathFile);
            }
            return "";
        }

        private void FrmThreadCaptcha_Load(object sender, EventArgs e)
        {
            //captcha.server.OnWriteLine += new Server.OnConsole(WriteLog);
            //captcha.start();
            //captcha.ConnectServer();
        }

        private void FrmThreadCaptcha_FormClosing(object sender, FormClosingEventArgs e)
        {
            //captcha.Close();
            Stop = true;
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            string fileCapchar = Application.StartupPath + @"\capchar.jpg";
            File.Copy(fileCapchar, Application.StartupPath + @"\captcha\capchar.jpg", true);
        }
    }
}
